use crate::db::dao::network_acl::NetworkAclDao;
use crate::db::{dao, po};
use crate::dto;
use crate::service::Error;
use std::sync::Arc;
use wanmesh_common::error::ResponseError;

#[async_trait::async_trait]
pub trait NetworkAclService: Sync + Send {
    async fn add(
        &self,
        params: &dto::core::network_acl::AddParams,
    ) -> Result<dto::core::network_acl::AddResponseData, Error>;

    async fn get(
        &self,
        network_acl_id: &str,
    ) -> Result<dto::core::network_acl::NetworkAclItem, Error>;

    async fn try_get(
        &self,
        network_acl_id: &str,
    ) -> Result<Option<dto::core::network_acl::NetworkAclItem>, Error>;

    async fn list(
        &self,
        filter: &dto::core::network_acl::Filter,
        offset: u64,
        limit: u64,
    ) -> Result<Vec<dto::core::network_acl::NetworkAclItem>, Error>;

    async fn update(
        &self,
        network_acl_id: &str,
        params: &dto::core::network_acl::UpdateParams,
    ) -> Result<(), Error>;

    async fn delete(&self, network_acl_id: &str) -> Result<(), Error>;

    async fn count(&self, filter: &dto::core::network_acl::Filter) -> Result<u64, Error>;
}

pub struct DefaultNetworkAclService {
    network_acl_dao: Arc<dyn NetworkAclDao>,
}

impl DefaultNetworkAclService {
    pub fn new(network_acl_dao: Arc<dyn NetworkAclDao>) -> Self {
        DefaultNetworkAclService { network_acl_dao }
    }
}

#[async_trait::async_trait]
impl NetworkAclService for DefaultNetworkAclService {
    async fn add(
        &self,
        params: &dto::core::network_acl::AddParams,
    ) -> Result<dto::core::network_acl::AddResponseData, Error> {
        let network_acl_id = wanmesh_common::util::new_id()?;
        self.network_acl_dao
            .insert(po::network_acl::ActiveModel {
                id: Default::default(),
                network_acl_id: po::ActiveValue::Set(network_acl_id.clone()),
                name: po::ActiveValue::Set(params.name.clone()),
                description: po::ActiveValue::Set(params.description.clone()),
                create_timestamp_millis: Default::default(),
                update_timestamp_millis: Default::default(),
            })
            .await?;

        Ok(dto::core::network_acl::AddResponseData { network_acl_id })
    }

    async fn get(
        &self,
        network_acl_id: &str,
    ) -> Result<dto::core::network_acl::NetworkAclItem, Error> {
        if let Some(item) = self.try_get(network_acl_id).await? {
            return Ok(item);
        }

        return Err(ResponseError::network_acl_not_found(network_acl_id).into());
    }

    async fn try_get(
        &self,
        network_acl_id: &str,
    ) -> Result<Option<dto::core::network_acl::NetworkAclItem>, Error> {
        let filter = dao::network_acl::Filter {
            network_acl_id: Some(network_acl_id.to_string()),
            ..Default::default()
        };

        if let Some(m) = self
            .network_acl_dao
            .try_get(dao::network_acl::Filter::from(filter))
            .await?
        {
            return Ok(Some(m.into()));
        }

        Ok(None)
    }

    async fn list(
        &self,
        filter: &dto::core::network_acl::Filter,
        offset: u64,
        limit: u64,
    ) -> Result<Vec<dto::core::network_acl::NetworkAclItem>, Error> {
        let po_list = self
            .network_acl_dao
            .find(dao::FindParams {
                filter: filter.into(),
                offset: Some(offset),
                limit: Some(limit),
                ..Default::default()
            })
            .await?;

        let list = po_list.into_iter().map(|m| m.into()).collect();

        Ok(list)
    }

    async fn update(
        &self,
        network_acl_id: &str,
        params: &dto::core::network_acl::UpdateParams,
    ) -> Result<(), Error> {
        if params == &Default::default() {
            return Ok(());
        }

        let filter = dao::network_acl::Filter {
            network_acl_id: Some(network_acl_id.to_string()),
            ..Default::default()
        };

        self.network_acl_dao.update(filter, params.into()).await?;

        Ok(())
    }

    async fn delete(&self, network_acl_id: &str) -> Result<(), Error> {
        let filter = dao::network_acl::Filter {
            network_acl_id: Some(network_acl_id.to_string()),
            ..Default::default()
        };

        self.network_acl_dao
            .delete(dao::network_acl::Filter::from(filter))
            .await?;

        Ok(())
    }

    async fn count(&self, filter: &dto::core::network_acl::Filter) -> Result<u64, Error> {
        let count = self
            .network_acl_dao
            .count(dao::network_acl::Filter::from(filter))
            .await?;
        Ok(count)
    }
}

impl From<&dto::core::network_acl::Filter> for dao::network_acl::Filter {
    fn from(value: &dto::core::network_acl::Filter) -> Self {
        Self {
            network_acl_id: None,
            name: value.name.clone(),
        }
    }
}

impl From<dto::core::network_acl::Filter> for dao::network_acl::Filter {
    fn from(value: dto::core::network_acl::Filter) -> Self {
        Self::from(&value)
    }
}

impl From<&po::network_acl::Model> for dto::core::network_acl::NetworkAclItem {
    fn from(value: &po::network_acl::Model) -> Self {
        Self {
            network_acl_id: value.network_acl_id.clone(),
            inner: dto::core::network_acl::NetworkAcl {
                name: value.name.clone(),
                description: value.description.clone(),
            },
        }
    }
}

impl From<po::network_acl::Model> for dto::core::network_acl::NetworkAclItem {
    fn from(value: po::network_acl::Model) -> Self {
        Self::from(&value)
    }
}

impl From<&dto::core::network_acl::UpdateParams> for dao::network_acl::UpdateParams {
    fn from(value: &dto::core::network_acl::UpdateParams) -> Self {
        Self {
            name: po::option_to_active_value(value.name.clone()),
            description: po::option_to_active_value(value.description.clone()),
        }
    }
}

impl From<dto::core::network_acl::UpdateParams> for dao::network_acl::UpdateParams {
    fn from(value: dto::core::network_acl::UpdateParams) -> Self {
        Self::from(&value)
    }
}
